/**
 * 级联选择器
 * @params datasets 数据
 */
export function cascaderFilterFormat(datasets) {
  let seriesData = [];
  const { type, source, dimensions } = datasets;
  if (type === 'STATIC') {
    seriesData = source;
  } else {
    seriesData = transObject(source, dimensions.xAxis.split('&'));
  }
  return {
    seriesData,
  };
}
/**
 * 将一个没有层级的扁平对象,转换为树形结构({value, children})结构的对象
 * @param {array} tableData - 一个由对象构成的数组,里面的对象都是扁平的
 * @param {array} keys - 一个由字符串构成的数组,字符串为前一数组tableData中对象的key,最终输出的对象层级顺序为keys中字符串key的顺序
 * @return {array} 保存具有树形结构的对象
 */

function transObject(tableData, keys) {
  const hashTable = {};
  const res = [];
  for (let i = 0; i < tableData.length; i++) {
    let arr = res;
    let cur = hashTable;
    for (let j = 0; j < keys.length; j++) {
      const key = keys[j];
      const filed = tableData[i][key];
      if (!cur[filed]) {
        const pusher = {
          value: filed,
          label: filed,
          title: filed,
        };
        let tmp;
        if (j !== keys.length - 1) {
          tmp = [];
          pusher.children = tmp;
        }
        cur[filed] = { $$pos: arr.push(pusher) - 1 };
        cur = cur[filed];
        arr = tmp;
      } else {
        cur = cur[filed];
        arr = arr[cur.$$pos].children;
      }
    }
  }
  return res;
}
